package com.gzy.wbapplication.modules.log;


import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.gzy.wbapplication.R;
import com.gzy.wbapplication.events.ReloadLogEvent;
import com.gzy.wbapplication.manager.AuthManager;
import com.gzy.wbapplication.model.MyLog;
import com.gzy.wbapplication.model.Page;
import com.gzy.wbapplication.model.Result;
import com.gzy.wbapplication.net.LogApi;
import com.gzy.wbapplication.net.core.XXModelCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

import static androidx.constraintlayout.widget.Constraints.TAG;

/**
 * A simple {@link Fragment} subclass.
 */
public class LogFragment extends Fragment {

    RecyclerView recyclerView;
    SwipeRefreshLayout swipeRefreshLayout;
    LogAdapter adapter;

    long currPage = 1;

    private List<MyLog> dataList = new ArrayList<>();
    private long size = 3;

    public LogFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        EventBus.getDefault().register(this);

        return inflater.inflate(R.layout.fragment_log, container, false);
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recyclerView = view.findViewById(R.id.recyclerView);
        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);
         view.findViewById(R.id.tv_settings).setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View view) {
                 startActivity(new Intent(getContext(),AddLogActivity.class));
             }
         });


        adapter = new LogAdapter(dataList);

        //创建布局管理
        LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

        recyclerView.setAdapter(adapter);

        swipeRefreshLayout.setRefreshing(true);

        swipeRefreshLayout.post(this::loadData);
        swipeRefreshLayout.setOnRefreshListener(this::loadData);
//        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                loadData();
//            }
//        });
        // 设置加载更多的功能

        adapter.getLoadMoreModule().setEnableLoadMore(true);
        adapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadMore(currPage+1);
            }
        });

        // 单击行

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter1, @NonNull View view, int position) {
                Log.e(TAG, "onItemClick: " + position );
                MyLog log = adapter.getData().get(position);
                Intent intent = new Intent(getContext(),EditLogActivity.class);

                intent.putExtra("log", JSON.toJSONString(log));

                startActivity(intent);
            }
        });
    }

    void loadMore(long page){
        LogApi.getLogList(AuthManager.loadToken(getContext()), page, size, new XXModelCallback<Result<Page<MyLog>>>(new TypeReference<Result<Page<MyLog>>>(){}) {
            @Override
            public void onResponseData(Call call, Result<Page<MyLog>> model) {
                if (model.getData().getData().size() > 0){
                    adapter.addData(model.getData().getData());
                    adapter.getLoadMoreModule().loadMoreComplete();
                    currPage += 1;
                }else{
                    adapter.getLoadMoreModule().loadMoreEnd();
                }
            }

            @Override
            public void onFailure2(Call call, IOException e, ErrType type, String message) {
                adapter.getLoadMoreModule().loadMoreFail();
            }
        });
    }

    void loadData() {
        LogApi.getLogList(AuthManager.loadToken(getContext()), 1, size, new XXModelCallback<Result<Page<MyLog>>>(new TypeReference<Result<Page<MyLog>>>() {
        }) {
            @Override
            public void onResponseData(Call call, Result<Page<MyLog>> model) {
                adapter.setNewData(model.getData().getData());
                currPage = 1;
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onFailure2(Call call, IOException e, ErrType type, String message) {
                swipeRefreshLayout.setRefreshing(false);
                Toast.makeText(getContext(), "" + message, Toast.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(ReloadLogEvent message) {
        loadData();
    }
}
